package com.rongshu.view.home.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.AdapterListener;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.submitArticle.adapter.SelectFloderAdapter;
import com.rongshu.view.userInfo.entity.Article;
import com.rongshu.view.userInfo.iview.ArticleView;
import com.rongshu.view.userInfo.presenter.ArticlePresenter;
import com.rongshu.widget.BanyanInputDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.DensityUtil;
import com.widget.titlebar.ImmersionBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2018/12/29.
 * description：投稿选择文集
 */
public class SelectFloderActivity extends BaseActivity<ArticlePresenter> implements ArticleView {
    @BindView(R.id.head_middle)
    TextView headMiddle;
    @BindView(R.id.layout_empty)
    RelativeLayout layoutEmpty;
    @BindView(R.id.collected_works_recyclerview)
    RecyclerView collectedWorksRecyclerview;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.head_content)
    RelativeLayout headContent;
    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private SelectFloderAdapter mArticleAdapter = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //map
    private Map<String, Object> map = null;
    private List<Article.ResponseBean> articles;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset()
                .keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .statusBarAlpha(0);
        } else {
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f);
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_select_floder;
    }

    @Override
    protected void initView() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) headContent.getLayoutParams();
        layoutParams.topMargin = DensityUtil.getStateBar(this);
        headContent.setLayoutParams(layoutParams);
        headMiddle.setText("选择文集");
        setPresenter(new ArticlePresenter(this), this);
        //layoutmanager
        manager = new LinearLayoutManager(this);
        articles = new ArrayList<>();
        //adapter
        mArticleAdapter = new SelectFloderAdapter(this, articles);
        //recyclerview
        collectedWorksRecyclerview.setLayoutManager(manager);
        collectedWorksRecyclerview.setAdapter(mArticleAdapter);
        mArticleAdapter.setAdapter(new AdapterListener() {
            @Override
            public void callBack(Object object) {
                if (object instanceof Article.ResponseBean) {
                    Article.ResponseBean article = (Article.ResponseBean) object;
                    Intent intent = new Intent();
                    intent.putExtra(Constant.INTENT_DATA, article);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
        //触发自动刷新
        smartRefreshLayout.autoRefresh();
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                smartRefreshLayout.resetNoMoreData();
                pageIndex = 1;
                getAppSerial();
            }
        });
        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                getAppSerial();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }


    /**
     * App获取文集名字列表
     */
    private void getAppSerial() {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("isSerial", "false");
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getAppSerial(user_id, "false", pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * APP新增文集
     */
    private void getAddSerial(String serial_name) {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("serial_name", serial_name);
        map.put("isSerial", "false");
        presenter.getAddSerial(user_id, serial_name, "false", Common.encryptionSign(map));
        map.clear();
    }


    @OnClick({R.id.head_left, R.id.new_collected_works_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                finish();
                break;
            case R.id.new_collected_works_layout:
                BanyanInputDialog.Builder builder = new BanyanInputDialog.Builder(this);
                builder.setTitle(getString(R.string.please_input_collected_name));
                builder.setLeft(getString(R.string.cancle));
                builder.setRight(getString(R.string.complete));
                final BanyanInputDialog banyanInputDialog = builder.create();
                builder.setDialogOnClick(new BanyanInputDialog.Builder.onClickListener() {
                    @Override
                    public void leftClickListener(Object object) {
                        banyanInputDialog.dismiss();
                    }

                    @Override
                    public void rightClickListener(Object object) {
                        banyanInputDialog.dismiss();
                        String msg = (String) object;
                        if (TextUtils.isEmpty(msg.trim())){
                            toast("请输入文集名称");
                        } else {
                            //新建文集
                            getAddSerial((String) object);
                            showKeyboard(false);
                        }
                    }
                });
                banyanInputDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        showKeyboard(false);
                    }
                });
                banyanInputDialog.show();
                break;
        }
    }

    @Override
    public void onArticleList(Article article) {
        if (article != null && article.getResponse() != null) {
            List<Article.ResponseBean> authorDetailBeans = article.getResponse();
            if (smartRefreshLayout.isRefreshing()) {
                smartRefreshLayout.finishRefresh();
            }
            if (smartRefreshLayout.isLoading()) {
                smartRefreshLayout.finishLoadmore();
            }
            if (pageIndex == 1) {
                articles.clear();
            }
            if (authorDetailBeans.size() < pageSize) {
                smartRefreshLayout.setLoadmoreFinished(true);
            }
            articles.addAll(authorDetailBeans);
            mArticleAdapter.notifyDataSetChanged();
            layoutEmpty.setVisibility(articles.size() == 0 ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void onUpdateArticle(INetBean iNetBean) {

    }

    @Override
    public void onAddArticle(INetBean bean) {
        if (bean.getErrCode() != 0) {
            toast(bean.getErrMsg());
            showKeyboard(false);
        }
        pageIndex = 1;
        getAppSerial();
    }

    @Override
    public void onDeleteArticle(INetBean bean) {

    }
}
